//
//  DecialDelegate.m
//  LCPhotoBrowser
//
//  Created by 程强 on 17/3/30.
//  Copyright © 2017年 程强. All rights reserved.
//

#import "DecimalDigitManager.h"

@interface DecimalDigitManager()
{
    BOOL _isHaveDian;
}
@end


@implementation DecimalDigitManager

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        _isHaveDian = NO;
    }else{
        _isHaveDian = YES;
    }
    if ([string length] > 0) {
        
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if (((single >= '0' && single <= '9'))||single == '.') {//数据格式正确
            
            //首字母不能为0和小数点
            if([textField.text length] == 0){
                if(single == '.') {
                    //@"第一个数字不能为小数点或0");
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
                if (_decimalDigit<=0&&single == '0') {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;

                }
                //                if (single == '0') {
                //                    ToastMsgInWindow(@"亲，第一个数字不能为0");
                //                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                //                    return NO;
                //                }
            }
            
            //输入的字符是否是小数点
            if (single == '.') {
                if (self.decimalDigit == 0) {
                    return NO;
                }
                if(!_isHaveDian)//text中还没有小数点
                {
                    _isHaveDian = YES;
                    return YES;
                }else{
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }else{
                if (_isHaveDian) {//存在小数点
                    
                    //判断小数点的位数
                    NSRange ran = [textField.text rangeOfString:@"."];
                    if (range.location - ran.location <= self.decimalDigit) {
                        return YES;
                    }else{
                        //@"输入的格式错误");
                        return NO;
                    }
                }else{
                    return YES;
                }
            }
        }else{//输入的数据格式不正确
            //@"您输入的格式不正确");
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
    
}

@end
